package cfca.seal.common;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class LRUCache<K, V>
{
  private final int MAX_CACHE_SIZE;
  private static final float DEFAULT_LOAD_FACTOR = 0.75F;
  LinkedHashMap<K, V> map;

  public LRUCache(int cacheSize)
  {
    this.MAX_CACHE_SIZE = cacheSize;

    int capacity = (int)Math.ceil(this.MAX_CACHE_SIZE / 0.75F) + 1;
    this.map = new LinkedHashMap(capacity, 0.75F, true)
    {
      @Override
      protected boolean removeEldestEntry(Map.Entry eldest) {
        return size() > LRUCache.this.MAX_CACHE_SIZE;
      }
    };
  }

  public synchronized void put(K key, V value) {
    this.map.put(key, value);
  }

  public synchronized V get(K key) {
    return this.map.get(key);
  }

  public synchronized void remove(K key) {
    this.map.remove(key);
  }

  public synchronized List<V> getAll() {
    List list = new ArrayList(this.map.values());
    return list;
  }

  public synchronized int size() {
    return this.map.size();
  }

  public synchronized void clear() {
    this.map.clear();
  }

  @Override
  public String toString()
  {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry entry : this.map.entrySet()) {
      sb.append(String.format("%s:%s ", new Object[] { entry.getKey(), entry.getValue() }));
    }
    return sb.toString();
  }
}